<?php

App::uses('AppController', 'Controller');

class PagesController extends AppController {

    public $name = 'Pages';
    public $helpers = array('Html', 'Session');
    public $uses = array();

    public function display() {
        $path = func_get_args();

        $count = count($path);
        if (!$count) {
            $this->redirect('/');
        }
        $page = $subpage = $title_for_layout = null;

        if (!empty($path[0])) {
            $page = $path[0];
        }
        if (!empty($path[1])) {
            $subpage = $path[1];
        }
        if (!empty($path[$count - 1])) {
            $title_for_layout = Inflector::humanize($path[$count - 1]);
        }

        if ($page == "home") {
            $model = $this->getModelName();

            // NOTICIAS
            $noticias = $this->$model->Query("SELECT * FROM noticias ORDER BY fecha DESC LIMIT 3");
            foreach ($noticias as $key => $value) {
                $subpath = "";
                for ($j = 0; $j < 5; $j++) {
                    $subpath.= substr($noticias[$key]['noticias']['imagen'], ($j * 2), 2) . "/";
                }
                $noticias[$key]['noticias']['imagen'] = $subpath . $noticias[$key]['noticias']['imagen'];
            }
            $this->set('noticias', $noticias);

            // OPINIONES
            $opiniones = $this->$model->Query("SELECT * FROM opiniones ORDER BY fecha DESC LIMIT 2");
            foreach ($opiniones as $key => $value) {
                $subpath = "";
                for ($j = 0; $j < 5; $j++) {
                    $subpath.= substr($opiniones[$key]['opiniones']['imagen'], ($j * 2), 2) . "/";
                }
                $opiniones[$key]['opiniones']['imagen'] = $subpath . $opiniones[$key]['opiniones']['imagen'];
            }
            $this->set('opiniones', $opiniones);
        }

        $this->set(compact('page', 'subpage', 'title_for_layout'));
        $this->render(implode('/', $path));
    }

    // Permite consultar la homepage sin usuario
    public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('display');
    }

}
